package cn.kailangtu.myapplication.services;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;

import cn.kailangtu.myapplication.FirstFragment;
import cn.kailangtu.myapplication.data.Address;
import cn.kailangtu.myapplication.data.CanData;
import cn.kailangtu.myapplication.events.SerialData;
import cn.kailangtu.myapplication.events.SerialDataRS481;
import cn.kailangtu.myapplication.events.SerialPortCmd;
import cn.kailangtu.myapplication.events.发送CAN数据;
import cn.kailangtu.myapplication.events.灯刷新;
import cn.kailangtu.myapplication.tools.APPSPUtils;
import cn.kailangtu.serialport.CommonUtils;
import cn.kailangtu.serialport.ReceiveData;
import cn.kailangtu.serialport.ReceiveMsgListener;
import cn.kailangtu.serialport.SerialPortApi;
import cn.kailangtu.serialportv2.DataVersion2;

public class SerialDataService extends Service {

    private LinkedBlockingQueue<ReceiveData> receiveMsgQueue = new LinkedBlockingQueue<>();
   // private LinkedBlockingQueue<ReceiveData> receiveMsgQueuers4851 = new LinkedBlockingQueue<>();

    public SerialDataService() {
    }
    @Override
    public void onCreate() {
        super.onCreate();
       EventBus.getDefault().register(this);
        init();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(SerialData event){
       // binding.textviewFirst.setText(event.toString());
      //  Log.e("wwwwww","uuuu");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(发送CAN数据 event)
    {
        if(serialPortApi != null)
        {
            serialPortApi.send(event.getAddress(),event.getData(),true);
        }
    }

    @Override
    public void onDestroy() {
      //  EventBus.getDefault().unregister(this);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }


    @SuppressLint("ForegroundServiceType")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        //启动服务用
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("persident", "persident",
                    NotificationManager.IMPORTANCE_LOW);
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            manager.createNotificationChannel(channel);
            Notification notification = new NotificationCompat.Builder(this, "persident")
                    .setAutoCancel(true)
                    .setCategory(Notification.CATEGORY_SERVICE)
                    .setOngoing(true)
                    .setPriority(NotificationManager.IMPORTANCE_LOW).build();
            startForeground(12, notification);
        }

        return super.onStartCommand(intent, flags, startId);
    }
    SerialPortApi serialPortApi=new SerialPortApi();
    private void init()
    {

        serialPortApi.openSerialPort("/dev/ttyHSL0", 115200, 0, new ReceiveMsgListener(){
            @Override
            public void errorMsg(String s) {
                Log.e("SerialDataService","打开串口失败！！");
            }

            @Override
            public void portReceiveData(ReceiveData receiveData) {
                Log.d("kkkkkkk","portReceiveData:"+receiveData.toString());

                //获取队列数据
                receiveMsgQueue.offer(receiveData);
            }

            @Override
            public void portReceiveDataEx(byte[] data) {

            }


        });
//
        ProcessThread thread = new ProcessThread();
        thread.start();
        testSpeed1();
    }
    byte[] data_EventBus=  new byte[80];
    private class ProcessThread extends  Thread{
        @Override
        public void run() {
            super.run();
            while (!isInterrupted()) {
                try {
                    //  if(reportMsgQueue.size())
                    ReceiveData receiveData = receiveMsgQueue.take();
                    byte[] data1= receiveData.getData();
                    byte[] id= receiveData.getFrameId();

                    EventBus.getDefault().post(new SerialPortCmd(CommonUtils.ByteArrayToHexString(id),CommonUtils.ByteArrayToHexString(data1)));

                    int frame = CommonUtils.byteArrayToInt(id);
                    CanData.getInstance().setNewValue(frame,data1);
                    判断灯();


                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


            }

        }
    }

    boolean 最后一次左灯值 = false;
    boolean 最后一次右灯值 = false;
    boolean 最后一次双闪值 = false;

    private void 判断灯(){
        boolean 右转向灯 = CanData.getInstance().getDataBit(0x381, 0, 6);
        boolean 左转向灯 = CanData.getInstance().getDataBit(0x381, 0, 7);
        boolean 双闪灯 = CanData.getInstance().getDataBit(0x381, 1, 0);
        int leftValue = 0;
        int rightValue = 0;
        int doubleValue = 0;



        if(最后一次双闪值 != 双闪灯 ){
            最后一次双闪值 = 双闪灯;
            doubleValue = 最后一次双闪值 ? 1:2;
        }


        if(最后一次左灯值 != 左转向灯 ){
            最后一次左灯值 = 左转向灯;
            leftValue = 最后一次左灯值 ? 1:2;
        }

        if(最后一次右灯值 != 右转向灯 ){
            最后一次右灯值 = 右转向灯;
            rightValue = 最后一次右灯值 ? 1:2;
        }



        if(leftValue != 0 || rightValue != 0 || doubleValue != 0){
            EventBus.getDefault().post(new 灯刷新(leftValue,rightValue,doubleValue));
        }


    }




    int 读取=0;

     int id2ee_21=0;

    public void testSpeed1()
    {

        new Thread(new Runnable() {
            @Override
            public void run() {
                int index = 0;
                while(true) {
                   if(读取==0){
                       Address.getInstance(). 行驶里程[0] = APPSPUtils.getInstance().get行驶里程();

                        读取=12;
                    }
                     // 行驶里程=2/7200+行驶里程;
                    Address.getInstance(). 行驶里程[0]= Address.getInstance().车速 /7200F+ Address.getInstance().行驶里程[0];
                    APPSPUtils.getInstance().set行驶里程( Address.getInstance().行驶里程[0]);


                    if( index >= 2 * 10 *6) {
                        /*
                        float fen =  Address.getInstance(). 小时计[0] = APPSPUtils.getInstance().get小时计() * 60;
                        //Address.getInstance().小时计[0] = Address.getInstance().小时计[0] + 0.5f;
                        fen = (fen+1) / 60;
                        APPSPUtils.getInstance().set小时计(fen);

                         */
                        long fen = APPSPUtils.getInstance().get分钟计();
                        fen++;
                        APPSPUtils.getInstance().set分钟计(fen);
                        index=0;
                    }
                    Address.getInstance(). 小时计[0] = (float)APPSPUtils.getInstance().get分钟计() / 60;
                    SystemClock.sleep(500);
                    index++;
                }
            }
        }).start();
    }

    //合并成int
    public static int combineBytesToInt(byte byte1, byte byte2) {
        // 将byte1左移8位，空出的低位由byte2填充
        return (byte1 << 8) | (byte2 & 0xFF);
    }





}



//// 存储字符串类型数据
////                    editor.putString("username", "john_doe");
//// 存储整型数据
//                        editor.putInt("行驶里程", 行驶里程);
//// 存储布尔型数据
////                    editor.putBoolean("isPremium", true);
//// 提交数据，异步保存
//                                editor.apply();
//// 或者使用同步保存
//// editor.commit();
//
//
//// 读取字符串类型数据，第二个参数为默认值
//                                //     String username = sharedPreferences.getString("username", "default_user");
//
//// 读取整型数据，第二个参数为默认值
//                                行驶里程 = sharedPreferences.getInt("行驶里程", 行驶里程);
//
//// 读取布尔型数据，第二个参数为默认值
//                                //   boolean isPremium = sharedPreferences.getBoolean("isPremium", false);
//
////// 获取SharedPreferences实例和Editor对象
////                        SharedPreferences sharedPreferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
////                        SharedPreferences.Editor editor = sharedPreferences.edit();
//
//// 删除键为"username"的数据
////                        editor.remove("行驶里程");
//
//// 提交数据
//                                editor.apply();
//// 或者使用同步提交
//// editor.commit();